package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.BaiduForumDownloader;
import com.spider.silence.downloader.ZuiChengduDownLoader;
import com.spider.silence.utils.PropertiesUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;

import org.apache.log4j.Logger;

/**
 * 百度贴吧线程池
 * Created by zh on 2017/1/9.
 */
public class BaiduForumDownLoaderPool {

	private Logger logger = Logger.getLogger(ZuiChengduDownLoaderPool.class);
    private static BaiduForumDownLoaderPool instance = new BaiduForumDownLoaderPool();
    private  LinkedList<BaiduForumDownloader> pool = new LinkedList<BaiduForumDownloader>();

    /**
     *  初始化downloader数量
     */
    private BaiduForumDownLoaderPool(){
        int initNum = Integer.parseInt(PropertiesUtil.getVal("BaiduForum.DownLoader.Pool.initNum"));

        BaiduForumDownloader downLoader = null;
       
        for(int i=0;i<initNum;i++){
        	BaiduForumDownloader downloader = new BaiduForumDownloader();
        	//downLoader.init();
        	synchronized (pool) {
        		 pool.add(downloader);
			}
        }
    }

    /**
     * 释放downloader
     * @param downLoader
     */
    public  void releaseDownLoader(BaiduForumDownloader downLoader){
        if(downLoader != null){
            synchronized (pool){
                //System.out.println("release downloader..");
                pool.add(downLoader);
                pool.notifyAll();
            }
        }
    }

    /**
     * 获取downloader
     * @param mills
     * @return
     * @throws InterruptedException
     */
    public  BaiduForumDownloader  fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            //完全超时
            if(mills <= 0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else{
                long future = System.currentTimeMillis() + mills;
                long remain = mills;
                while(pool.isEmpty() && remain > 0){
                    pool.wait(remain);
                    remain = future - System.currentTimeMillis();
                }
                BaiduForumDownloader downloader = null;
                if(!pool.isEmpty()){
                    downloader = pool.removeFirst();
                }
                return downloader;
            }
        }
    }

    public  BaiduForumDownloader fetchDownLoader() throws InterruptedException {
        synchronized (pool){
            while (pool.isEmpty()){
                pool.wait();
            }
            return pool.removeFirst();
        }
    }

    /**
     * 清空池
     */
    public void empty(){
        pool= Lists.newLinkedList();
    }
    public static BaiduForumDownLoaderPool getInstance(){
        return  instance;
    }
}
